import { Component, OnInit } from '@angular/core';
import { CartService } from '../cart.service';
import { ActivatedRoute, Router } from '@angular/router';
import { Location } from '@angular/common';
@Component({
  selector: 'app-page-shoppingcart',
  templateUrl: './page-shoppingcart.component.html',
  styleUrls: ['./page-shoppingcart.component.scss']
})
export class PageShoppingcartComponent implements OnInit {
  CartList: any = []
  //是否被选中
  isSelect: boolean = false

  selectMap: any = {}

  constructor(private cartServ: CartService,
    private router: Router,
    private route: ActivatedRoute,
    private location: Location
  ) {
    this.CartList = this.cartServ.CartList

  }

  // 全选
  isAllSelect: Boolean = false

  selectAll($event: any) {
    const isAllChecked = $event.target.checked
    this.isAllSelect = isAllChecked

    if (isAllChecked) {
      this.CartList.forEach((cart: any) => {
        this.selectMap[cart.goods.id] = true
        console.log(this.isSelect + "111")
        console.log(this.selectMap[cart.goods.id] + "222")
      }
      )
      this.isSelect = true
    } else {
      this.selectMap = {}
      this.isSelect = false
    }
    this.sumPrice();
    this.updateAllSelectStatus()
  }

  //用于更新全选框的状态：
  updateAllSelectStatus() {
    const isAllSelected = this.CartList.length > 0 && this.CartList.every((cart: any) => this.selectMap[cart.goods.id]);
    this.isAllSelect = isAllSelected;
  }



  //选择商品
  clickSelected($event: any, cart: any) {
    const checked = $event.target.checked
    this.selectMap[cart.goods?.id] = checked
    this.isSelect = checked
    this.sumPrice()
    this.updateAllSelectStatus()
  }

  //按钮加减
  changeCount(cart: any, value: number) {
    let result = cart.count + value
    if (result < 0) {
      return
    }
    cart.count = result
    console.log(cart.count)
    this.sumPrice()
  }

  //计算总金额
  countSum: number | undefined
  priceSum: number = 0
  //加
  sumPrice() {
    console.log(this.selectMap)
    let sumPrice: number = 0
    this.CartList.forEach((cart: any) => {
      if (!this.selectMap[cart.goods.id]) return // 跳过非选择项
      console.log("cart.goods" + cart.goods)
      console.log("cart.count" + cart.count)
      sumPrice += cart.count * cart.goods.get('goodsPrice')
      console.log(this.priceSum + "总价")
    })
    this.priceSum = sumPrice
  }

  //删除商品
  deleteCartList(index: any) {
    if (confirm('确定移除此项吗？')) {
      this.CartList.splice(index, 1);
    }

  }



  clickIn(item: any) {
    console.log(item.goods)
    this.router.navigate(["./intelligent-shopping/detail"], {
      queryParams: {
        id: item.goods.id
      }
    })
  }


  async ngOnInit(): Promise<void> {

    // setTimeout(() => {

    // }, 1000);

  }

  goPay() {
    if (this.isSelect) {
      console.log("(this.cartServ.CartList", this.cartServ.CartList)
      this.router.navigate(["./intelligent-shopping/pay"], {
        queryParams: { id: this.CartList?.id }
      })
    }
    else return

  }


}
